package com.esd.crm.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.esd.crm.Constants;
import com.esd.crm.UsernameAndPasswordMd5;
import com.esd.crm.entity.User;
import com.esd.crm.service.UserService;

/**
 * 
 * @author snailzhang
 *
 */
@Controller
public class LoginController {
	private static final Logger logger = LogManager.getLogger(LoginController.class);

	@Autowired
	private UserService userService;

	/**
	 * 用户名已存在
	 */
	@Value("${MSG_USER_EXIST}")
	private String MSG_USER_EXIST;

	/**
	 * 用户不存在
	 */
	@Value("${MSG_USER_NOT_EXIST}")
	private String MSG_USER_NOT_EXIST;

	/**
	 * 退出页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/quit", method = RequestMethod.GET)
	public ModelAndView quitGet(HttpSession session) {
		logger.debug("清空Session里的登录信息");
		session.removeAttribute(Constants.USER_ID);
		logger.debug("退出，跳转到登录页");
		return new ModelAndView("login");
	}

	/**
	 * 登录页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String loginGet() {
		logger.debug("跳转到登录页");
		// return new ModelAndView("login");
		return "login";
	}

	/**
	 * 检查用户名是否重复
	 * 
	 * @param userName
	 * @return
	 */
	@RequestMapping(value = "/checkUserName", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> checkUserName(HttpServletRequest request) {
		String userName = request.getParameter("username");
		logger.info("检测用户名");
		logger.debug("username:{}", userName);
		Map<String, Object> map = new HashMap<String, Object>();
		User use = userService.selectByName(userName);
		if (use != null) {
			map.put("status", true);
			map.put(Constants.MESSAGE, MSG_USER_EXIST);
		} else {
			map.put("status", false);
			map.put(Constants.MESSAGE, MSG_USER_NOT_EXIST);
		}
		return map;
	}

	/**
	 * 登录提交处理
	 * 
	 * @param request
	 * @param redirectAttributes
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ModelAndView loginPost(HttpServletRequest request, RedirectAttributes redirectAttributes,
			HttpSession session) {
		String userName = request.getParameter("username");
		String passWord = request.getParameter("password");
		//String checkCode = request.getParameter("checkCode");
		
		//String sessionCheckCode = session.getAttribute("checkCode").toString();

//		logger.info("userName:{},passWord:{},checkCode:{}", userName, passWord, checkCode);
		logger.info("userName:{},passWord:{}", userName, passWord);

//		if (checkCode.equals(sessionCheckCode) == false) {
//			redirectAttributes.addFlashAttribute("username", userName);
//			redirectAttributes.addFlashAttribute("password", passWord);
//			redirectAttributes.addFlashAttribute("message", "验证码错误");
//			logger.info("验证码错误");
//			return new ModelAndView("redirect:/login");
//		}

		User user = userService.selectByName(userName);
		if (user != null && user.getUsername().equals(userName)) {
			UsernameAndPasswordMd5 md5 = new UsernameAndPasswordMd5();
			String pwd = md5.getMd5(userName, passWord);
			//logger.info("pwd:", pwd);
			if (pwd.equals(user.getPassword())) {
				session.setAttribute(Constants.USER_ID, user.getUserId());
				session.setAttribute(Constants.USER_NAME, user.getUsername());
				session.setAttribute(Constants.USER_TYPE, user.getUserType());
				logger.info("登录成功");
				user.setUpdateTime(new Date());
				userService.updateByPrimaryKey(user);
//		 		return new ModelAndView("redirect:/security/index");
				session.setAttribute(Constants.USER_ID, user.getUserId());
				session.setAttribute(Constants.USER_NAME, user.getUsername());
				return new ModelAndView("redirect:/security/order");

			} else {
				redirectAttributes.addFlashAttribute("username", userName);
				redirectAttributes.addFlashAttribute("password", passWord);
				redirectAttributes.addFlashAttribute("message", "用户名密码错误");
				logger.info("用户名密码错误");
				return new ModelAndView("redirect:/login");
			}
		}
		redirectAttributes.addFlashAttribute("username", userName);
		redirectAttributes.addFlashAttribute("password", passWord);
		redirectAttributes.addFlashAttribute("message", "用户名密码错误");
		logger.info("用户名密码错误");
		return new ModelAndView("redirect:/login");
	}
}
